package App;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        try (Scanner scan = new Scanner(System.in)) {
            Utils u = new Utils();
            // 注册驱动并获取连接
            Class.forName(u.getDriver());
            try (Connection conn = DriverManager.getConnection(u.getUrl(), u.getUser(), u.getPassword())) {
                System.out.println("连接成功!");
                boolean bol = true;
                while (bol) {
                    printMenu();
                    int choice = getValidChoice(scan, 1, 7);
                    switch (choice) {
                        case 1 -> u.addProduct(conn, scan);
                        case 2 -> u.viewAllProducts(conn);
                        case 3 -> u.viewProductByName(conn, scan);
                        case 4 -> u.updateProduct(conn, scan);
                        case 5 -> u.deleteProduct(conn, scan);
                        case 6 -> u.calculateTotalPrice(conn);
                        case 7 -> {
                            bol = false;
                            System.out.println("谢谢使用!");
                        }
                    }
                }
            } catch (SQLException e) {
                System.err.println("数据库操作异常: " + e.getMessage());
            }
        } catch (ClassNotFoundException e) {
            System.err.println("驱动加载失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void printMenu() {
        System.out.println("商品管理系统\n" +
                "1. 录入商品入库\n" +
                "2. 查看所有商品信息\n" +
                "3. 查看指定名称的商品信息\n" +
                "4. 根据编号修改商品信息\n" +
                "5. 根据编号删除商品信息\n" +
                "6. 统计仓库中所有商品的总计价格\n" +
                "7. 退出系统");
        System.out.print("请您输入功能序号: ");
    }

    private static int getValidChoice(Scanner scan, int min, int max) {
        int choice;
        while (true) {
            try {
                choice = scan.nextInt();
                scan.nextLine(); // 消耗换行符
                if (choice >= min && choice <= max) {
                    return choice;
                } else {
                    System.out.printf("请输入%d-%d之间的数字: ", min, max);
                }
            } catch (java.util.InputMismatchException e) {
                System.out.printf("请输入%d-%d之间的数字: ", min, max);
                scan.nextLine(); // 清除无效输入
            }
        }
    }
}
